﻿#ifndef GLWIDGET_H
#define GLWIDGET_H

#include "models/urdfparser.h"
#include "models/meshloader.h"
#include <QOpenGLWidget>
#include <QOpenGLFunctions>
#include <QOpenGLShaderProgram>
#include <QOpenGLBuffer>
#include <QOpenGLVertexArrayObject>
#include <QMap>
#include <QPushButton>

class UrdfWidget : public QOpenGLWidget, protected QOpenGLFunctions
{
    Q_OBJECT

public:
    void setRobotRotation(const QMatrix4x4& rotation);
    void setBShowRobotData(bool newBShowRobotData);
    void setArc(const float * fsetArc);
    void resetParser(){m_pParser=NULL;}
    friend class MainWindow;

protected:
    UrdfWidget(QWidget *parent = nullptr);
    ~UrdfWidget();
    void initializeGL() override;
    void paintGL() override;
    void resizeGL(int w, int h) override;

private slots:
    void onMeshLoaded(const MeshLoadData& data);
    void onLoadFinished(bool success);
    void onProgressUpdated(int progress);
    void loadMesh();
    void updateData();
private:
    void setupShaders();
    void setupCoordinateSystem();
    void drawCoordinateSystem();
    void drawRobot();
    void updateViewMatrix();
    void startLoadMeshes();
    void cleanupMeshes();
    void drawText(QPainter& painter, const QString& text);
    void drawProgressBar(QPainter& painter, int progress);

    QOpenGLShaderProgram* m_program = NULL;
    QOpenGLBuffer m_axisVBO;
    QOpenGLVertexArrayObject m_axisVAO;

    UrdfParser * m_pParser = NULL;
    QMap<QString, QOpenGLBuffer*> m_meshVBOs;
    QMap<QString, QOpenGLVertexArrayObject*> m_meshVAOs;
    QMap<QString, QVector<GLuint>> m_meshIndices;

    QMatrix4x4 m_projection;
    QMatrix4x4 m_view;

    QMatrix4x4 m_robotRotation;

    MeshLoader* m_pMeshLoader = nullptr;

    bool m_showText = false;
    QString m_displayText;
    bool m_loading = false;
    int m_loadProgress = 0;

    bool m_bShowRobotData = true;

    // QWidget interface
protected:
    void showEvent(QShowEvent *event);
};

#endif // GLWIDGET_H 
